package zz.note.thread.demo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import zz.note.thread.demo.LoginManage;
import zz.note.thread.entity.UserEntity;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Author: ZZ
 * @date 2022/2/16
 */
@RestController
@Slf4j
public class LoginService {
	@Autowired
	private LoginManage loginManage;

	@GetMapping("/login")
	public ResponseEntity<String> login(UserEntity userEntity) throws ExecutionException, InterruptedException {
		UserEntity dbUser = dbLogin(userEntity);
		if (dbUser == null) {
			return ResponseEntity.status(500).body("账号或者是密码错误");
		}
        // 异步开始写日志
//        loginLog(userEntity);
//        sendSms(userEntity);
//        sendEmail(userEntity);
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                loginLog(userEntity);
//                sendSms(userEntity);
//                sendEmail(userEntity);
//            }
//        }).start();

//		asynLogin(userEntity);
//		loginManage.asynLogin(userEntity);

		Future<String> stringFuture = loginManage.futureTaskLogin(userEntity);
		return ResponseEntity.status(200).body(stringFuture.get());
//		return ResponseEntity.status(200).body("登陆成功");
	}

	@Async
	public void asynLogin(UserEntity userEntity) {
		loginLog(userEntity);
		sendSms(userEntity);
		sendEmail(userEntity);
	}

	private UserEntity dbLogin(UserEntity userEntity) {
		log.info(">>>1.正在查询数据库登陆<<<");
		try {
			Thread.sleep(2000);
		} catch (Exception e) {

		}
		return new UserEntity();
	}

	private void loginLog(UserEntity userEntity) {
		log.info(">>>2.异步开始写登陆的日志<<<");
		try {
			Thread.sleep(2000);
		} catch (Exception e) {

		}
	}

	private void sendSms(UserEntity userEntity) {
		log.info(">>>3.异步开始发送短信<<<");
		try {
			Thread.sleep(2000);
		} catch (Exception e) {

		}
	}

	private void sendEmail(UserEntity userEntity) {
		log.info(">>>4.异步开始发送邮件<<<");
		try {
			Thread.sleep(2000);
		} catch (Exception e) {

		}
	}
}
